package sy.service.impl;

import java.io.File;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.alibaba.fastjson.JSONObject;

import sy.bean.AppEntryLogBean;
import sy.model.AppComment;
import sy.model.AppComplaint;
import sy.model.AppEntryLog;
import sy.model.AppEquipment;
import sy.model.AppFriends;
import sy.model.AppFunction;
import sy.model.AppPlant;
import sy.model.AppRepair;
import sy.model.SysAccount;
import sy.model.SysAccountAppFunctionMapping;
import sy.model.SysOwnerRenterMapping;
import sy.model.SysProject;
import sy.model.SysUser;
import sy.model.SysVisitor;
import sy.model.WYAccount;
import sy.model.WYUser;
import sy.service.AppBusinessServiceI;
import sy.service.AppCommentServiceI;
import sy.service.AppComplaintServiceI;
import sy.service.AppEntryLogServiceI;
import sy.service.AppEquipmentServiceI;
import sy.service.AppFriendsServiceI;
import sy.service.AppPlantServiceI;
import sy.service.AppRepairServiceI;
import sy.service.SysAccountAppFunctionMappingServiceI;
import sy.service.SysAccountServiceI;
import sy.service.SysOwnerRenterMappingServiceI;
import sy.service.SysProjectServiceI;
import sy.service.SysUserServiceI;
import sy.service.SysVisitorServiceI;
import sy.service.WYAccountServiceI;
import sy.service.WYUserServiceI;
import sy.util.CodeUtil;
import sy.util.DateUtil;
import sy.util.Encrypt;
import sy.util.FileUpload;
import sy.util.ResultJson;
@Service("appBusinessService")
public class AppBusinessServiceImpl implements AppBusinessServiceI{
	@Autowired
	SysUserServiceI sysUserService;
	@Autowired
	SysOwnerRenterMappingServiceI sysOwnerRenterMappingService;
	@Autowired
	SysAccountAppFunctionMappingServiceI sysAccountAppFunctionMappingService;
	@Autowired
	SysAccountServiceI sysAccountService;
	@Autowired
	AppEquipmentServiceI appEquipmentService;
	@Autowired
	AppRepairServiceI appRepairService;
	@Autowired
	AppCommentServiceI appCommentService;
	@Autowired
	AppComplaintServiceI appComplaintService;
	@Autowired
	AppFriendsServiceI appFriendsService;
	@Autowired
	SysProjectServiceI sysProjectService;
	@Autowired
	AppPlantServiceI appPlantService;
	@Autowired
	AppEntryLogServiceI appEntryLogService;
	@Autowired
	WYAccountServiceI wyAccountService;
	@Autowired
	SysVisitorServiceI sysVisitorService;
	@Autowired
	WYUserServiceI wyUserService;
	
	/**
	 * 判断当前token是否过期或者是否登录
	 * @Title: judgeToken
	 * @Description: TODO
	 * @param: @return     
	 * @return: boolean     
	 * @author:  xieyuanqiu
	 * @date: 2017年8月28日 下午2:35:55
	 * @throws
	 */
	private int judgeToken(String token){
		SysAccount sysAccount = sysAccountService.getSysAccountByToken(token);
		Date loginTime = sysAccount.getLoginTime();
		if (loginTime == null) {
			return 400;//没有登录
		} else {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			try {
				long d = DateUtil.differDay(sdf.format(loginTime), sdf.format(new Date()));
				/**
				 * 当前时间跟上一次登录时间大于15天，则token过期
				 */
				if (d>15) {
					return 401;//token已过期
				}
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		return 0;
	}
	
	
	@Override
	public ResultJson listSysUserByOwnerId(String ownerId, String token) {
		// TODO Auto-generated method stub
		ResultJson resultJson = new ResultJson();
		/**
		 * 返回值说明：
		 * 0：正常；400：没有登录；401：token过期
		 */
		int tokenFlag = judgeToken(token);
		if (tokenFlag == 0) {
			List<SysUser> sysUserList = sysUserService.listSysUserByOwnerId(ownerId);
			if (!sysUserList.isEmpty()) {
				resultJson.setState(true);
				resultJson.setResult(sysUserList);
			} else {
				resultJson.setState(false);
				resultJson.setMessage("没有相对应的同住人/访客");
			}
		} else {
			resultJson.setState(false);
			resultJson.setErrorCode(tokenFlag);
			switch (tokenFlag){
			    case 400:
			    	resultJson.setMessage("您已退出登录，请重新登录");
			    	break;
			    case 401:
			    	resultJson.setMessage("token已过期，请重新登录");
			    	break;
			    default:break;
			}
		}
		return resultJson;
	}
	@Override
	public ResultJson addOwnerRenter(String ownerId, String telephone, String token) {
		// TODO Auto-generated method stub
		/**
		 * 根据传过来的同住人的电话号码得到对应信息，同时获取业主信息，写入业主，同住人中间表
		 * 授权成功后再把同住人信息写入user表
		 */
		ResultJson resultJson = new ResultJson();
		
		/**
		 * 返回值说明：
		 * 0：正常；400：没有登录；401：token过期
		 */
		int tokenFlag = judgeToken(token);
		if (tokenFlag == 0) {
			List<SysAccount> renterVisiterList = sysAccountService.listSysAccountByKey(telephone);
			SysAccount owner = sysAccountService.getSysAccountById(ownerId);
			if (!renterVisiterList.isEmpty()) {
				List<SysOwnerRenterMapping> list = sysOwnerRenterMappingService.listSysOwnerRenterMappingByKey(renterVisiterList.get(0).getId());
				if (list.isEmpty()) {
					SysOwnerRenterMapping sysOwnerRenterMapping = new SysOwnerRenterMapping();
					sysOwnerRenterMapping.setId(UUID.randomUUID().toString());
					sysOwnerRenterMapping.setSysAccountByOwner(owner);
					sysOwnerRenterMapping.setSysAccountByRenter(renterVisiterList.get(0));
					try {
						sysOwnerRenterMappingService.save(sysOwnerRenterMapping);
						/**
						 * 授权后把同住人账号绑定到user表
						 */
						SysUser sysUser = new SysUser();
						sysUser.setId(UUID.randomUUID().toString());
						sysUser.setTelephone(telephone);
						sysUser.setSysAccount(renterVisiterList.get(0));
						sysUser.setIsOwner("n");
						sysUserService.save(sysUser);
					} catch (Exception e){
						resultJson.setState(false);
						resultJson.setMessage("授权失败！");
					}
					resultJson.setState(true);
					resultJson.setMessage("授权成功！");
				} else{
					resultJson.setState(false);
					resultJson.setMessage("该用户已被授权！");
				}
				
			} else {
				resultJson.setState(false);
				resultJson.setMessage("该用户没有注册！");
			}
		} else {
			resultJson.setState(false);
			resultJson.setErrorCode(tokenFlag);
			switch (tokenFlag){
			    case 400:
			    	resultJson.setMessage("您已退出登录，请重新登录");
			    	break;
			    case 401:
			    	resultJson.setMessage("token已过期，请重新登录");
			    	break;
			    default:break;
			}
		}
		return resultJson;
	}
	@Override
	public ResultJson deleteOwnerRenter(String ownerId,
			String renterId, String token) {
		// TODO Auto-generated method stub
		ResultJson resultJson = new ResultJson();
		/**
		 * 返回值说明：
		 * 0：正常；400：没有登录；401：token过期
		 */
		int tokenFlag = judgeToken(token);
		if (tokenFlag == 0) {
			Serializable i = sysOwnerRenterMappingService.deleteRenterVisitor(ownerId, renterId);
			if (i.equals(1)) {
				resultJson.setState(true);
				resultJson.setMessage("删除成功");
			} else {
				resultJson.setState(false);
				resultJson.setMessage("该业主或访客id不存在");
			}
		}else{
			resultJson.setState(false);
			resultJson.setErrorCode(tokenFlag);
			switch (tokenFlag){
			    case 400:
			    	resultJson.setMessage("您已退出登录，请重新登录");
			    	break;
			    case 401:
			    	resultJson.setMessage("token已过期，请重新登录");
			    	break;
			    default:break;
			}
		}
		return resultJson;
	}
	@Override
	public ResultJson adjustFunction(String accountId,List<Integer> functionIds, String token) {
		// TODO Auto-generated method stub
		/**
		 * 先删除该账号下的所有app功能，再根据当前的functionIds重新插入，最后返回所有有权限的功能
		 */
		ResultJson result = new ResultJson();
		/**
		 * 返回值说明：
		 * 0：正常；400：没有登录；401：token过期
		 */
		int tokenFlag = judgeToken(token);
		if (tokenFlag == 0) {
			Serializable i = sysAccountAppFunctionMappingService.deleteBySysAccountId(accountId);
			List<SysAccountAppFunctionMapping> list = new ArrayList<SysAccountAppFunctionMapping>();
			for(Integer fid : functionIds){
				SysAccountAppFunctionMapping obj = new SysAccountAppFunctionMapping();
				SysAccount account = new SysAccount();
				account.setId(accountId);
				AppFunction appFunction = new AppFunction();
				appFunction.setId(fid);
				obj.setSysAccountId(account);
				obj.setAppFunctionId(appFunction);
				list.add(obj);
			}
			sysAccountAppFunctionMappingService.saveBatch(list);
			//获取有权限的功能
			List<AppFunction> appFunctionList = sysAccountAppFunctionMappingService.listAppFunction(accountId);
			if(!appFunctionList.isEmpty()){
				result.setState(true);
				result.setResult(appFunctionList);
			}else{
				result.setState(false);
				result.setMessage("没有相应的功能");;
			}
		}else{
			result.setState(false);
			result.setErrorCode(tokenFlag);
			switch (tokenFlag){
			    case 400:
			    	result.setMessage("您已退出登录，请重新登录");
			    	break;
			    case 401:
			    	result.setMessage("token已过期，请重新登录");
			    	break;
			    default:break;
			}
		}
		return result;
	}
	@Override
	public ResultJson getScanData(String type, String code, String token) {
		// TODO Auto-generated method stub
		/**
		 * 根据类型参数来查询相关信息（设备，绿植，放行条，访客，业主二维码等）
		 */
		ResultJson resultJson = new ResultJson();
		/**
		 * 返回值说明：
		 * 0：正常；400：没有登录；401：token过期
		 */
		int tokenFlag = judgeToken(token);
		if (tokenFlag == 0) {
			if ("".equals(type) || type == null) {
				resultJson.setState(false);
				resultJson.setErrorCode(-1);
				resultJson.setMessage("缺少类型参数");
			} else {
				if ("equipment".equals(type)) {
					AppEquipment equipment = appEquipmentService.getAppEquipmentByCode(code);
					if (equipment != null) {
						resultJson.setState(true);
						resultJson.setErrorCode(200);
						resultJson.setResult(equipment);
					} else {
						resultJson.setState(false);
						resultJson.setErrorCode(-3);
						resultJson.setMessage("没有匹配的信息");
					}
				} else if ("plant".equals(type)){
					AppPlant plant = appPlantService.getAppPlantByCode(code);
					if (plant != null) {
						resultJson.setState(true);
						resultJson.setErrorCode(200);
						resultJson.setResult(plant);
					} else {
						resultJson.setState(false);
						resultJson.setErrorCode(-3);
						resultJson.setMessage("没有匹配的信息");
					}
				} else {
					resultJson.setState(false);
					resultJson.setErrorCode(-2);
					resultJson.setMessage("条形码错误");
				}
			}
		}else{
			resultJson.setState(false);
			resultJson.setErrorCode(tokenFlag);
			switch (tokenFlag){
			    case 400:
			    	resultJson.setMessage("您已退出登录，请重新登录");
			    	break;
			    case 401:
			    	resultJson.setMessage("token已过期，请重新登录");
			    	break;
			    default:break;
			}
		}
		return resultJson;
	}
	@Override
	public ResultJson addRepair(HttpServletRequest request, HttpServletResponse response, String id, String equipmentId, String type,
			String phenomenon, String token) {
		// TODO Auto-generated method stub
		/**
		 * 根据传来的参数保存保修信息
		 */
		ResultJson resultJson = new ResultJson();
		/**
		 * 返回值说明：
		 * 0：正常；400：没有登录；401：token过期
		 */
		int tokenFlag = judgeToken(token);
		if (tokenFlag == 0) {
			ResultJson fileUplaodJson = fileUpload(request, response);
			/**
			 * 判断投诉有没有文件上传
			 * 2表示没有文件上传，1表示上传失败，0表示上传成功
			 */
			if ("1".equals(fileUplaodJson.getFlag())) {
				resultJson.setState(false);
				resultJson.setMessage("上传图片/语音失败，报修失败");
			} else {
				String code = new CodeUtil().getCode();
				SysAccount account = new SysAccount();
				account.setId(id);
				AppEquipment equipment = new AppEquipment();
				equipment.setId(equipmentId);
				//构造维修单信息
				AppRepair appRepair = new AppRepair();
				appRepair.setCode(code);
				appRepair.setType(type);
				appRepair.setEquipmentId(equipment);
				appRepair.setSysAccountId(account);
				appRepair.setContent(phenomenon);
				appRepair.setStatus("0");//暂定0为报修进度
				
				/**
				 * 图片上传成功或者没有图片上传都添加投诉信息
				 */
				if (fileUplaodJson.getMessage() != null && fileUplaodJson.getMessage().contains("appImages")) {
					appRepair.setImgUrl(fileUplaodJson.getMessage());
				}
				
				Serializable i = appRepairService.save(appRepair);
				if (!i.equals(0)){
					resultJson.setState(true);
					resultJson.setMessage("报修成功，当前保修单号为："+code);
				} else {
					resultJson.setState(false);
					resultJson.setMessage("报修失败");
				}
			}
		}else{
			resultJson.setState(false);
			resultJson.setErrorCode(tokenFlag);
			switch (tokenFlag){
			    case 400:
			    	resultJson.setMessage("您已退出登录，请重新登录");
			    	break;
			    case 401:
			    	resultJson.setMessage("token已过期，请重新登录");
			    	break;
			    default:break;
			}
		}
		return resultJson;
	}
	@Override
	public ResultJson getRepairList(String token) {
		// TODO Auto-generated method stub
		ResultJson resultJson = new ResultJson();
		/**
		 * 返回值说明：
		 * 0：正常；400：没有登录；401：token过期
		 */
		int tokenFlag = judgeToken(token);
		if (tokenFlag == 0) {
			List<AppRepair> list = appRepairService.list();
			if (!list.isEmpty()) {
				resultJson.setState(true);
				resultJson.setResult(list);
			} else {
				resultJson.setState(false);
				resultJson.setMessage("没有任何维修信息");
			}
		}else{
			resultJson.setState(false);
			resultJson.setErrorCode(tokenFlag);
			switch (tokenFlag){
			    case 400:
			    	resultJson.setMessage("您已退出登录，请重新登录");
			    	break;
			    case 401:
			    	resultJson.setMessage("token已过期，请重新登录");
			    	break;
			    default:break;
			}
		}
		return resultJson;
	}
	@Override
	public ResultJson comment(String id, String type, String content, String repairCode, String token) {
		// TODO Auto-generated method stub
		ResultJson resultJson = new ResultJson();
		/**
		 * 返回值说明：
		 * 0：正常；400：没有登录；401：token过期
		 */
		int tokenFlag = judgeToken(token);
		if (tokenFlag == 0) {
			AppComment comment = new AppComment();
			SysAccount sysAccount = new SysAccount();
			sysAccount.setId(id);
			if ("repair".equals(type)) {///评价的是设备设施维修，则要传入维修单号并保存
				comment.setRepaireCode(repairCode);
			}
			comment.setContent(content);
			comment.setCategory(type);
			comment.setSysAccount(sysAccount);
			Serializable i = appCommentService.save(comment);
			if (!i.equals(0)) {
				resultJson.setState(true);
				resultJson.setMessage("评价成功");
			} else {
				resultJson.setState(false);
				resultJson.setMessage("评价失败");
			}
		}else{
			resultJson.setState(false);
			resultJson.setErrorCode(tokenFlag);
			switch (tokenFlag){
			    case 400:
			    	resultJson.setMessage("您已退出登录，请重新登录");
			    	break;
			    case 401:
			    	resultJson.setMessage("token已过期，请重新登录");
			    	break;
			    default:break;
			}
		}
		return resultJson;
	}
	@Override
	public ResultJson modifyPersonInfo(String sex, String name,String token) {
		// TODO Auto-generated method stub
		ResultJson resultJson = new ResultJson();
		/**
		 * 返回值说明：
		 * 0：正常；400：没有登录；401：token过期
		 */
		int tokenFlag = judgeToken(token);
		if (tokenFlag == 0) {
			SysAccount sysAccount = sysAccountService.getSysAccountByToken(token);
			if (sysAccount != null) {
				SysUser sysUser = sysUserService.getSysUserByAccount(sysAccount.getId());//根据账号id得到个人信息
				if(sex!=null && !"".equals(sex)){
					sysUser.setSex(sex);
				}
				if(name!=null && !"".equals(name)){
					sysUser.setName(name);
				}
				resultJson.setState(true);
				resultJson.setErrorCode(200);
				resultJson.setMessage("修改成功");
			} else {
				resultJson.setState(false);
				resultJson.setErrorCode(116);
				resultJson.setMessage("账户不存在，信息修改失败");
			}
		}else{
			resultJson.setState(false);
			resultJson.setErrorCode(tokenFlag);
			switch (tokenFlag){
			    case 400:
			    	resultJson.setMessage("您已退出登录，请重新登录");
			    	break;
			    case 401:
			    	resultJson.setMessage("token已过期，请重新登录");
			    	break;
			    default:break;
			}
		}
		return resultJson;
	}
	@Override
	public ResultJson fileUpload(HttpServletRequest request,
			HttpServletResponse response) {
		// TODO Auto-generated method stub
		ResultJson resultJson = FileUpload.fileUpload(request, response);
		return resultJson;
	}
	@Override
	public ResultJson updateComplaintStatus(String code, String status, String token) {
		// TODO Auto-generated method stub
		ResultJson resultJson = new ResultJson();
		/**
		 * 返回值说明：
		 * 0：正常；400：没有登录；401：token过期
		 */
		int tokenFlag = judgeToken(token);
		if (tokenFlag == 0) {
			try {
				appComplaintService.updateStatusByCode(code, status);
				resultJson.setState(true);
				resultJson.setMessage("更新状态成功！");
			} catch (Exception e) {
				resultJson.setState(false);
				resultJson.setMessage("更新状态失败！");
			}
		}else{
			resultJson.setState(false);
			resultJson.setErrorCode(tokenFlag);
			switch (tokenFlag){
			    case 400:
			    	resultJson.setMessage("您已退出登录，请重新登录");
			    	break;
			    case 401:
			    	resultJson.setMessage("token已过期，请重新登录");
			    	break;
			    default:break;
			}
		}
		return resultJson;
	}
	@Override
	public ResultJson listComplaint(String sysAccountId, String token) {
		// TODO Auto-generated method stub
		ResultJson resultJson = new ResultJson();
		/**
		 * 返回值说明：
		 * 0：正常；400：没有登录；401：token过期
		 */
		int tokenFlag = judgeToken(token);
		if (tokenFlag == 0) {
			List<AppComplaint> list = appComplaintService.listAppComplaintBySysAccountId(sysAccountId);
			if (!list.isEmpty()) {
				resultJson.setState(true);
				resultJson.setResult(list);
			} else {
				resultJson.setState(false);
				resultJson.setMessage("您没有任何投诉记录！");
			}
		}else{
			resultJson.setState(false);
			resultJson.setErrorCode(tokenFlag);
			switch (tokenFlag){
			    case 400:
			    	resultJson.setMessage("您已退出登录，请重新登录");
			    	break;
			    case 401:
			    	resultJson.setMessage("token已过期，请重新登录");
			    	break;
			    default:break;
			}
		}
		return resultJson;
	}
	@Override
	public ResultJson listAppFriendsByAccountId(String accountId, String token) {
		// TODO Auto-generated method stub
		ResultJson resultJson = new ResultJson();
		/**
		 * 返回值说明：
		 * 0：正常；400：没有登录；401：token过期
		 */
		int tokenFlag = judgeToken(token);
		if (tokenFlag == 0) {
			/**
			 * 判断是否缺少参数值
			 */
			if("".equals(accountId)){
				resultJson.setState(false);
				resultJson.setErrorCode(-1);
				resultJson.setMessage("缺少参数");
			} else {
				List<AppFriends> list = appFriendsService.listAppFriendsByAccountId(accountId);
				if (!list.isEmpty()){
					resultJson.setState(true);
					resultJson.setResult(list);
				} else {
					resultJson.setState(false);
					resultJson.setMessage("您没有发表任何动态");
				}
			}
		}else{
			resultJson.setState(false);
			resultJson.setErrorCode(tokenFlag);
			switch (tokenFlag){
			    case 400:
			    	resultJson.setMessage("您已退出登录，请重新登录");
			    	break;
			    case 401:
			    	resultJson.setMessage("token已过期，请重新登录");
			    	break;
			    default:break;
			}
		}
		return resultJson;
	}
	@Override
	public ResultJson listAppFriendsProjectId(String projectId, String token) {
		// TODO Auto-generated method stub
		ResultJson resultJson = new ResultJson();
		/**
		 * 返回值说明：
		 * 0：正常；400：没有登录；401：token过期
		 */
		int tokenFlag = judgeToken(token);
		if (tokenFlag == 0) {
			if("".equals(projectId)){
				resultJson.setState(false);
				resultJson.setErrorCode(-1);
				resultJson.setMessage("缺少参数");
			} else {
				List<AppFriends> list = appFriendsService.listAppFriendsByProjectId(projectId);
				if (!list.isEmpty()){
					resultJson.setState(true);
					resultJson.setResult(list);
				} else {
					resultJson.setState(false);
					resultJson.setMessage("没有该小区的动态");
				}
			}
		}else{
			resultJson.setState(false);
			resultJson.setErrorCode(tokenFlag);
			switch (tokenFlag){
			    case 400:
			    	resultJson.setMessage("您已退出登录，请重新登录");
			    	break;
			    case 401:
			    	resultJson.setMessage("token已过期，请重新登录");
			    	break;
			    default:break;
			}
		}
		return resultJson;
	}
	@Override
	public ResultJson addAppFriends(HttpServletRequest request,
			HttpServletResponse response, String accountId, String projectId,
			String content, String token) {
		ResultJson resultJson = new ResultJson();
		/**
		 * 返回值说明：
		 * 0：正常；400：没有登录；401：token过期
		 */
		int tokenFlag = judgeToken(token);
		if (tokenFlag == 0) {
			/**
			 * 判断投诉有没有文件上传
			 * 2表示没有文件上传，1表示上传失败，0表示上传成功
			 */
			ResultJson fileUplaodJson = fileUpload(request, response);
			if ("1".equals(fileUplaodJson.getFlag())) {
				resultJson.setState(false);
				resultJson.setMessage("上传图片/语音失败,发表动态失败");
			} else {
				/**
				 * 图片上传成功或者没有图片上传都添加发表朋友圈信息
				 */
				AppFriends appFriends = new AppFriends();
				appFriends.setId(UUID.randomUUID().toString());
				//获取发表人信息
				SysAccount account = sysAccountService.getSysAccountById(accountId);
				appFriends.setSysAccount(account);
				//获取项目（小区）信息
				SysProject poject = sysProjectService.getSysProjectById(projectId);
				appFriends.setSysProject(poject);
				
				appFriends.setDate(new Date());
				appFriends.setContent(content);
				if (fileUplaodJson.getMessage() != null && fileUplaodJson.getMessage().contains("appImages")) {
					appFriends.setImgurl(fileUplaodJson.getMessage());
				}
				try {
					appFriendsService.save(appFriends);
					resultJson.setState(true);
					resultJson.setMessage("发表动态成功");
				} catch (Exception e) {
					resultJson.setState(false);
					resultJson.setMessage("发表动态失败");
					return resultJson;
				}
			}
		}else{
			resultJson.setState(false);
			resultJson.setErrorCode(tokenFlag);
			switch (tokenFlag){
			    case 400:
			    	resultJson.setMessage("您已退出登录，请重新登录");
			    	break;
			    case 401:
			    	resultJson.setMessage("token已过期，请重新登录");
			    	break;
			    default:break;
			}
		}
		return resultJson;
	}
	@Override
	public ResultJson deleteAppFriendsById(String id, String token) {
		// TODO Auto-generated method stub
		ResultJson resultJson = new ResultJson();
		/**
		 * 返回值说明：
		 * 0：正常；400：没有登录；401：token过期
		 */
		int tokenFlag = judgeToken(token);
		if (tokenFlag == 0) {
			if("".equals(id)){
				resultJson.setState(false);
				resultJson.setErrorCode(-1);
				resultJson.setMessage("缺少参数");
			} else {
				try {
					appFriendsService.delete(id);
					resultJson.setState(true);
					resultJson.setMessage("删除动态成功");
				} catch (Exception e) {
					resultJson.setState(false);
					resultJson.setMessage("删除动态失败");
					return resultJson;
				}
			}
		}else{
			resultJson.setState(false);
			resultJson.setErrorCode(tokenFlag);
			switch (tokenFlag){
			    case 400:
			    	resultJson.setMessage("您已退出登录，请重新登录");
			    	break;
			    case 401:
			    	resultJson.setMessage("token已过期，请重新登录");
			    	break;
			    default:break;
			}
		}
		return resultJson;
	}


	@Override
	public ResultJson saveEntryLog(Map<String,Object> map) {
		// TODO Auto-generated method stub
		//appEntryLogService
		ResultJson resultJson = new ResultJson();
		AppEntryLog appEntryLog = new AppEntryLog();
		String blueToothOrginName = (String) map.get("blueToothOrginName");
		String blueToothCustomName = (String) map.get("blueToothCustomName");
		String yzId = (String) map.get("yzId");
		String wyId = (String) map.get("wyId");
		String reqId = (String) map.get("reqId");
		String upid = (String) map.get("upid");
		String openTime = (String) map.get("openTime");
		String doorId = (String) map.get("doorId");
		String type = (String) map.get("type");
		
		if(type==null || doorId==null || openTime==null){
			resultJson.setErrorCode(-1);
			resultJson.setState(false);
			resultJson.setMessage("缺少参数值");
		}else{
			/******************开门必填字段**********************/
			Date openTimeDate = DateUtil.formatDate(openTime);
			appEntryLog.setOpenTime(openTimeDate);
			appEntryLog.setType(type);
			appEntryLog.setDoorId(doorId);
			
			if("bluetooth".equals(type)){
				appEntryLog.setBlueToothCustomName(blueToothCustomName);
				appEntryLog.setBlueToothOrginName(blueToothOrginName);
			}else{
				appEntryLog.setReqId(reqId);
				appEntryLog.setUpid(upid);
			}
			
			if(yzId!=null && yzId.length()>0){
				SysAccount sysAccount = sysAccountService.getSysAccountById(yzId);
				appEntryLog.setSysAccount(sysAccount);
			}
			
			if(wyId!=null && wyId.length()>0){
				WYAccount wyAccount = wyAccountService.getWYAccountById(wyId);
				appEntryLog.setWyAccount(wyAccount);
			}
			
			try {
				appEntryLogService.save(appEntryLog);
				resultJson.setErrorCode(200);
				resultJson.setState(true);
				resultJson.setMessage("操作成功");
			}catch (Exception e) {
				resultJson.setErrorCode(201);
				resultJson.setState(false);
				resultJson.setMessage("操作失败");
			}
		}
		return resultJson;
	}


	@Override
	public ResultJson listAppEntryLog(String token) {
		// TODO Auto-generated method stub
		ResultJson resultJson = new ResultJson();
		/**
		 * 返回值说明：
		 * 0：正常；400：没有登录；401：token过期
		 */
		int tokenFlag = judgeToken(token);
		if (tokenFlag == 0) {
			List<AppEntryLog> list = appEntryLogService.list();
			List<String> yzaccountIds = new ArrayList<String>();
			List<String> wyaccountIds = new ArrayList<String>();
			List<AppEntryLogBean> beanList = new ArrayList<AppEntryLogBean>();
			if(!list.isEmpty()){
				for(AppEntryLog obj : list){
					if(obj.getSysAccount()!=null){
						yzaccountIds.add(obj.getSysAccount().getId());
					}else if(obj.getWyAccount()!=null){
						wyaccountIds.add(obj.getWyAccount().getId());
					}
				}
				List<SysUser> sysUserList = new ArrayList<>();
				List<WYUser> wyUserList = new ArrayList<>();
				if(!yzaccountIds.isEmpty()){
					sysUserList = sysUserService.listSysUserByAccountIds(yzaccountIds);
				}
				if(!wyaccountIds.isEmpty()){
					wyUserList = wyUserService.listWYUserByAccountId(wyaccountIds);
				}
				for(AppEntryLog obj : list){
					AppEntryLogBean bean = new AppEntryLogBean();
					bean.setAppEntryLog(obj);
					for(SysUser yzUser:sysUserList){
						if(obj.getSysAccount()!=null && yzUser.getSysAccount()!=null && obj.getSysAccount().getId().equals(yzUser.getSysAccount().getId())){
							bean.setYzName(yzUser.getName());
							break;
						}
					}
					for(WYUser wyUser:wyUserList){
						if(obj.getWyAccount()!=null && wyUser.getWyAccount()!=null && obj.getWyAccount().getId().equals(wyUser.getWyAccount().getId())){
							bean.setWyName(wyUser.getName());
							break;
						}
					}
					beanList.add(bean);
				}
				
				Map<String,Object> map = new HashMap<String,Object>();
				map.put("rows", beanList);
				resultJson.setState(true);
				resultJson.setErrorCode(200);
				resultJson.setResult(map);
			} else {
				resultJson.setState(false);
				resultJson.setErrorCode(202);
				resultJson.setMessage("没有相关数据返回");
			}
		}else{
			resultJson.setState(false);
			resultJson.setErrorCode(tokenFlag);
			switch (tokenFlag){
			    case 400:
			    	resultJson.setMessage("您已退出登录，请重新登录");
			    	break;
			    case 401:
			    	resultJson.setMessage("token已过期，请重新登录");
			    	break;
			    default:break;
			}
		}
		
		return resultJson;
	}


	@Override
	public ResultJson inviteVistor(String token, Map<String, Object> map) {
		// TODO Auto-generated method stub
		ResultJson resultJson = new ResultJson();
		/**
		 * 返回值说明：
		 * 0：正常；400：没有登录；401：token过期
		 */
		int tokenFlag = judgeToken(token);
		if (tokenFlag == 0) {
			/**
			 * 保存完访客信息后生成二维码链接，返回给移动端
			 */
			SysAccount sysAccount = sysAccountService.getSysAccountByToken(token);
			String name = (String) map.get("name");
			String telephone = (String) map.get("telephone");
			String accessTime = (String) map.get("accessTime");
			String doorId = (String) map.get("doorId");
			String carNo = (String) map.get("carNo");
			SysVisitor visitor = new SysVisitor();
			Date accessDateTime = DateUtil.formatDate(accessTime);
			visitor.setId(UUID.randomUUID().toString());
			visitor.setIsYZInvitation("y");
			visitor.setName(name);
			visitor.setTelephone(telephone);
			visitor.setAccessTime(accessDateTime);
			visitor.setDoorId(doorId);
			visitor.setCarNo(carNo);
			visitor.setSysAccount(sysAccount);
			SysUser user = sysUserService.getSysUserByAccount(sysAccount!=null?sysAccount.getId():"");
			JSONObject qrCodeJson = new JSONObject();
			qrCodeJson.put("name", name);
			qrCodeJson.put("telephone", telephone);
			qrCodeJson.put("doorId", doorId);
			qrCodeJson.put("accessTime", accessTime);
			qrCodeJson.put("yzName", user.getName());
			visitor.setQrCode(qrCodeJson.toJSONString());
			/********************生成二维码************************/
			try{
				sysVisitorService.save(visitor);
				Map<String,Object> param = new HashMap<String,Object>();
				param.put("qrCodeContent", qrCodeJson);
				resultJson.setState(true);
				resultJson.setErrorCode(200);
				resultJson.setResult(param);
			}catch(Exception e){
				resultJson.setState(false);
				resultJson.setErrorCode(201);
				resultJson.setMessage("系统异常，操作失败");
			}
		}else{
			resultJson.setState(false);
			resultJson.setErrorCode(tokenFlag);
			switch (tokenFlag){
			    case 400:
			    	resultJson.setMessage("您已退出登录，请重新登录");
			    	break;
			    case 401:
			    	resultJson.setMessage("token已过期，请重新登录");
			    	break;
			    default:break;
			}
		}
		return resultJson;
	}

}
